package com.jiuyuejiu.func_video.video.fenlei;

import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.func_video.VideoService;
import com.jiuyuejiu.func_video.adapter.VideoFenleiAdapter;
import com.jiuyuejiu.func_video.domain.VideoDetailStc;
import com.jiuyuejiu.func_video.domain.VideoFenleiStc;
import com.jiuyuejiu.func_video.videosync.VideoSyncActivity;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.jiuyuejiu.utils.ViewUtil;
import com.kylin.core.utils.dbtutil.FileUtil;
import com.kylin.core.utils.dbtutil.FunUtil;
import com.kylin.core.utils.dbtutil.PrefUtils;
import com.kylin.core.utils.flyn.Eyes;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import cn.jzvd.Jzvd;


/**
 * 所有的分类列表 Activity
 */
public class VideoFenleiActivity extends BaseActivity implements View.OnClickListener {


    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    private GridView platform_gv;

    MyHandler handler;
    private VideoService service;


    private int videocount = 12;


    private Random rand;

    private ClipboardManager myClipboard;// 剪贴板

    // 视频播放控制器
    SensorManager sensorManager;
    Jzvd.JZAutoFullscreenListener sensorEventListener;

    private String categoryname;
    private String title;

    // 文件的MD5名称
    private String fileName;

    private ArrayList<VideoFenleiStc> videoFenleiStcs;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<VideoFenleiActivity> fragmentRef;

        public MyHandler(VideoFenleiActivity fragment) {
            fragmentRef = new SoftReference<VideoFenleiActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            VideoFenleiActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT1:// // 获取分类列表的回调
                    fragment.getJsonSuc(bundle);
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);

        // 标题栏白底黑字
        Eyes.setStatusBarLightMode(this, Color.WHITE);

        initView();
        initData();

    }

    private void initView() {

        backBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_confirm);
        backTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.top_navigation_tv_title);
        confirmBtn.setVisibility(View.VISIBLE);
        confirmBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);


        platform_gv = (GridView) findViewById(R.id.category_personmanage_gv);
    }

    private void initData() {
        handler = new MyHandler(this);
        service = new VideoService(VideoFenleiActivity.this, handler);

        // 获取上一页传递过来的数据
        Intent i = getIntent();
        categoryname = i.getStringExtra("categoryname");
        title = i.getStringExtra("title");

        titleTv.setText(title);

        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);// CLIPBOARD_SERVICE

        confirmTv.setText("刷新");
        confirmTv.setTextSize(14);


        rand = new Random();


        // 视频播放控制器
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();




        // 下载所有分类
        downloadVideoCatList();
    }

    // ----↓ 下载所有分类 2022/6/4 10:45 ↓------------------------------------------------------------------------------------
    private void downloadVideoCatList() {
        if (hasPermission(ConstValues.WRITE_READ_EXTERNAL_PERMISSION)) {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有分类
            downloadVideoCatJson();
        } else {
            // 还没有对一个权限(请求码,权限数组)这两个参数都事先定义好
            requestPermission(ConstValues.WRITE_READ_EXTERNAL_CODE, ConstValues.WRITE_READ_EXTERNAL_PERMISSION);
        }
    }

    // 手动拥有读写权限后 执行下载文件
    @Override
    public void doWriteSDCard() {
        try {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有分类
            downloadVideoCatJson();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 先下载所有分类
    private void downloadVideoCatJson() {

        // 获取所有分类
        fileName = FunUtil.StringToMd5(ConstValues.LANDKING + categoryname);
        FileUtil.deleteFile(new File(ShanHaiUtil.parseFilePath(fileName)));// 先删除
        // String downurl = ShanHaiUtil.getHttpid() + ConstValues.JIEQUPATH + ConstValues.TXTNAME;
        String downurl = ShanHaiUtil.getHttpid() + ConstValues.LANDKING + "/" + categoryname + "/" + ConstValues.TXTNAME;


        // 请求
        service.downCatVideoJsonList(downurl,// 请求url
                fileName, // 本地存储名称
                true, // 是否显示进度条 false不显示下载进度,true显示下载进度框
                ConstValues.WAIT1);// 用于当前Activity界面handle的对应回调接收 比如what1,what2
    }

    // ----↑ 载所有分类 2022/6/4 10:45 ↑------------------------------------------------------------------------------------

    // ----↓ 下载所有分类的回调 2021/12/19 13:33 ↓------------------------------------------------------------------------------------
    private void getJsonSuc(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {
            String filepath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
            File file = new File(filepath);
            if (file.exists()) {//存在本地;
                try {
                    // 传入File文件 读取文件内容
                    String result = ShanHaiUtil.parseFileToString(file);
                    // 传入字符串 将字符串分割成数组
                    String[] read = ShanHaiUtil.splitStringToArray(result);
                    // 将数组 转成 集合
                    videoFenleiStcs = ShanHaiUtil.parseStringArrayToList(read);

                    if (videoFenleiStcs != null && videoFenleiStcs.size() > 0) {

                        // 1 是否重新请求每个分类的视频列表 默认true true需要重新下载  false不需要重新下载
                        boolean isgetvideourl = PrefUtils.getBoolean(VideoFenleiActivity.this, ConstValues.ISGETVIDEOURL, true);

                        // 2 第一个分类文件 本地是否有这个文件
                        VideoFenleiStc videoFenleiStc = videoFenleiStcs.get(1);
                        String fileName = FunUtil.StringToMd5(categoryname + videoFenleiStc.getCategory());// 分类名称转MD5
                        String pdfpath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
                        File docFile = new File(pdfpath);

                        if (isgetvideourl || !docFile.exists()) {// 下载每个分类的视频列表 下载每个_LIST文件

                            // 下载每个分类文件
                            downFileJsonByPath();

                        } else {// 读取视频记录
                            readFenleiVideoRecord();
                        }


                    } else {
                        Toast.makeText(VideoFenleiActivity.this, "获取分类列表失败", Toast.LENGTH_SHORT).show();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(VideoFenleiActivity.this, "没有找到视频文件", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(VideoFenleiActivity.this, "没有找到分类文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(VideoFenleiActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }
    // ----↑ 下载所有分类的回调 2021/12/19 13:33 ↑------------------------------------------------------------------------------------


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1011:
                String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
                Toast.makeText(VideoFenleiActivity.this, result, Toast.LENGTH_SHORT).show();
                // 读取视频记录
                readFenleiVideoRecord();
        }
    }


    private void readFenleiVideoRecord() {

        if (videoFenleiStcs != null) {

            //使用迭代器删除元素
            Iterator<VideoFenleiStc> iterator = videoFenleiStcs.iterator();
            while (iterator.hasNext()) {
                VideoFenleiStc videoFenleiStc = iterator.next();
                String fileName = FunUtil.StringToMd5(categoryname + videoFenleiStc.getCategory());// 分类名称转MD5
                String pdfpath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
                File docFile = new File(pdfpath);

                if (docFile.exists()) {//存在本地;
                    try {

                        // 传入File文件 读取文件内容
                        String result = ShanHaiUtil.parseFileToString(docFile);
                        // 传入字符串 将字符串分割成数组
                        String[] read = ShanHaiUtil.splitStringToArray(result);
                        // 将数组 转成 集合
                        ArrayList<VideoDetailStc> detailStcs = ShanHaiUtil.getVideoListByVideoArray(videoFenleiStc.getCategory(),
                                ConstValues.LANDKING + "/" + categoryname + "/", read);


                        // 删除无视频的
                        if (detailStcs.size() <= 0 ) {
                            iterator.remove();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(VideoFenleiActivity.this, "没有找到视频文件", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // Toast.makeText(VideoFenleiActivity.this, "没有找到分类文件", Toast.LENGTH_SHORT).show();
                }
            }

            VideoFenleiAdapter jieMainAdapter = new VideoFenleiAdapter(VideoFenleiActivity.this, videoFenleiStcs);

            platform_gv.setAdapter(jieMainAdapter);
            // 设置item的点击监听
            platform_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    VideoFenleiStc stc = videoFenleiStcs.get(position);
                    String category = stc.getCategory();

                    Intent intent = new Intent(VideoFenleiActivity.this, VideoListActivity.class);
                    intent.putExtra("VideoFenleiStc", stc);
                    startActivity(intent);

                }
            });

        } else {
            Toast.makeText(VideoFenleiActivity.this, "获取分类列表失败", Toast.LENGTH_SHORT).show();
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_navigation_rl_back:// 返回
                this.finish();
                break;
            case R.id.top_navigation_rl_confirm://
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;

                // 下载每个分类文件
                downFileJsonByPath();

                break;
        }
    }

    // 下载每个分类文件
    public void downFileJsonByPath() {
        Intent intent = new Intent(VideoFenleiActivity.this, VideoSyncActivity.class);
        intent.putExtra("categoryname", categoryname);  // 下载路径
        intent.putExtra("videoFenleiStcs", videoFenleiStcs);  // 保存本地文件名称 _LIST.TXT
        startActivityForResult(intent, 1011);
    }

    @Override
    public void onBackPressedSupport() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        Jzvd.releaseAllVideos();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
